package com.atguigu.category.service.impl;

import com.atguigu.category.mapper.CategoryMapper;
import com.atguigu.category.service.CategoryService;
import com.atguigu.clients.ProductClient;
import com.atguigu.param.PageParam;
import com.atguigu.param.ProductHotsParam;
import com.atguigu.pojo.Category;
import com.atguigu.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductClient productClient;

    @Override
    public R detail(String categoryName) {

        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<Category>();
        categoryQueryWrapper.eq("category_name",categoryName);
        Category category = categoryMapper.selectOne(categoryQueryWrapper);

        if(category==null){
            return R.fail("类别查询失败！");
        }
        return R.ok("类别查询成功",category);

    }

    @Override
    public R names(ProductHotsParam productHotsParam) {

        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("category_name",productHotsParam.getCategoryName());
        //select单列
        queryWrapper.select("category_id");

        List<Object> ids = categoryMapper.selectObjs(queryWrapper);
        return R.ok("查询成功",ids);

    }

    @Override
    public R list() {

        List<Category> categoryList = categoryMapper.selectList(null);
        return R.ok("查询成功",categoryList);
    }

    @Override
    public R listCategory(PageParam pageParam) {

        Page<Category> page = new Page<>(pageParam.getCurrentPage(),pageParam.getPageSize());
        page = categoryMapper.selectPage(page,null);
        return R.ok("查询成功",page.getRecords(),page.getTotal());
    }

    @Override
    public R save(Category category) {

        categoryMapper.insert(category);
        return R.ok("添加分类成功");
    }

    //要查看该分类下是否有商品，有商品则不能删除该分类
    @Override
    public R remove(Integer categoryId) {

        Long num = productClient.count(categoryId);
        if(num>0){
            return R.ok("该分类下有"+num+"个商品，删除失败");
        }
        categoryMapper.deleteById(categoryId);
        return R.ok("删除分类成功");
    }

    @Override
    public R update(Category category) {

        categoryMapper.updateById(category);
        return R.ok("分类修改成功");
    }
}
